//
//  Lyric.m
//  Exam10-1
//
//  Created by 孙晓晔 on 2017/4/11.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "Lyric.h"

@interface Lyric()

@property(nonatomic,strong) NSMutableDictionary *lrcDict;

@end

@implementation Lyric

// 初始化
-(instancetype)init:(NSString*)path ofType:(NSString*)ofType {
    self = [super init];
    
    if (self) {
        NSString *strPath = [[NSBundle mainBundle] pathForResource:path ofType:ofType];
        
        NSString *str = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
        
        [self lrc:str];
    }
    
    return self;
}

// 根据时间获取歌词
-(NSString*)lyricByTime:(NSTimeInterval)time {
    return [self.lrcDict objectForKey:[self formatTime:time]];
}

// 时间格式化
-(NSString*)formatTime:(NSTimeInterval)time {
    NSInteger second = (NSInteger)time;
    
    NSInteger minute = 0;
    if (second > 60) {
        minute = second / 60;
        second = second % 60;
    }
    
    NSString *ret = [NSString stringWithFormat:@"%02ld:%02ld", minute, second];
    
    return ret;
}

// 解析LRC文件并生成字典
-(void)lrc:(NSString*)str {
    
    self.lrcDict = [NSMutableDictionary dictionary];
    
    NSArray *array = [str componentsSeparatedByString:@"\n"];
    
    for (int i = 0; i < [array count]; i++) {
        
        NSString *lineString = [array objectAtIndex:i];
        
        if ([lineString length] < 5) {
            continue;
        }
        
        NSArray *lineArray = [lineString componentsSeparatedByString:@"]"];
        
        if ([lineString hasPrefix:@"[ti:"]) {
            self.name = [[lineArray objectAtIndex:0] substringFromIndex:4];
            continue;
        }
            
        NSString *str1 = [lineString substringWithRange:NSMakeRange(3, 1)];
            
        if ([str1 isEqualToString:@":"]) {
            NSString *lrcStr = [lineArray objectAtIndex:1];
                    
            NSString *timeStr = [[lineArray objectAtIndex:0] substringWithRange:NSMakeRange(1, 5)];
                    
            //把时间和歌词加入词典
            [self.lrcDict setObject:lrcStr forKey:timeStr];
            
        }
    }
}
@end
